package com.taru.order.dao;


import com.taru.order.entity.*;
import com.taru.order.util.DbUtil;
import com.taru.order.util.StringUtil;
import com.taru.order.util.Util;

import java.awt.dnd.DnDConstants;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class ArtDaoImpl {

    /**
     * 添加文章(包含单纯文章，图片文章，音乐和介绍，视频图片和介绍)
     * @param articl
     * @return
     * @throws IOException
     */
    public int addArticl(Articl articl) throws IOException {
        String sql1="insert into `tb_articl`(articl_code,logo,title,context,isend,ispublish,user_id,cate_id,create_time) values (?,?,?,?,?,?,?,?,now())";
        String sql2="insert into `tb_path`(path,articl_code) values(?,?)";
        DbUtil.beginTransaction();
        List<String> list=articl.getPaths();
        int code=0;
        int code2=0;
        if(list !=null && list.size()>0){
            try {
                int code1=DbUtil.update(sql1,articl.getCode(),articl.getLogo(),articl.getTitle(),articl.getContext(),articl.getIsEnd(),articl.getIsPublish(),articl.getUserId(),articl.getCateId());
                for(String filePath :list){
                    code2=DbUtil.update(sql2, filePath,articl.getCode());
                }
                DbUtil.commit();
                code=code1 & code2;
            }catch (Exception e){
                DbUtil.rollback();
                e.printStackTrace();
            }
        }else {
            code=DbUtil.update(sql1,articl.getCode(),articl.getLogo(),articl.getTitle(),articl.getContext(),articl.getIsEnd(),articl.getIsPublish(),articl.getUserId(),articl.getCateId());
            DbUtil.commit();
        }
        return code;
    }
    /**
     * 根据articl_id在`tb_articl_group`表中获取专题
     */
    public List listgroups(String articl_id){
        String sql="select * from `tb_group` where group_id = (select group_id from `tb_articl_group` where articl_id=?)";
        List<Map<String, Object>> list = DbUtil.query(sql,articl_id);
        List<Group> groupList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (Map<String, Object> map : list) {
                Group group=new Group();
                group.setGroupId(StringUtil.valueOf(map.get("group_id")));
                group.setLogo(StringUtil.valueOf(map.get("logo")));
                group.setGroupName(StringUtil.valueOf(map.get("group_name")));
                group.setBrief(StringUtil.valueOf(map.get("brief")));
                groupList.add(group);
            }
        }
        return groupList;
    }
    /**
     * 根据articl_id获取文章里面的路劲
     */
    public List<FilePath> listFilepaths(String articl_id){
        String sql="select * from `tb_path` where articl_code = (select articl_code from `tb_articl` where articl_id=?)";
        List<Map<String, Object>> list = DbUtil.query(sql,articl_id);
        List<FilePath> filePaths = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (Map<String, Object> map : list) {
                FilePath filePath =new FilePath();
                filePath.setId(StringUtil.valueOf(map.get("id")));
                filePath.setPath(StringUtil.valueOf(map.get("path")));
                filePath.setArticl_code(StringUtil.valueOf(map.get("articl_code")));
                filePaths.add(filePath);
            }
        }
        return filePaths;
    }
    /**
     * 根据articl_id获取文章详情
     */
    public Articl getArticlById(String articl_id){
        String sql="select t1.*,t2.* from `tb_articl` t1,tb_user t2 where t1.user_id=t2.user_id and articl_id=?";
        List<Map<String, Object>> listArt = DbUtil.query(sql,articl_id);
        Articl articl=null;
        if (listArt != null && listArt.size() > 0) {
            Map<String, Object> map=listArt.get(0);
            User user=new User();
            user=new User();
            user.setUser_id(StringUtil.valueOf(map.get("user_id")));
            user.setUsername(StringUtil.valueOf(map.get("username")));
            user.setPassword(StringUtil.valueOf(map.get("password")));
            user.setNickname(StringUtil.valueOf(map.get("nickname")));
            user.setHeader(StringUtil.valueOf(map.get("header")));
            user.setTelphone(StringUtil.valueOf(map.get("telphone")));
            user.setIsLoved(StringUtil.valueOf(map.get("is_loved")));
            user.setCreate_time(StringUtil.valueOf(map.get("create_time")));
            user.setCollection_id(StringUtil.valueOf(map.get("collection_id")));
            user.setBrief(StringUtil.valueOf(map.get("brief")));
            articl = new Articl();
            articl.setId(StringUtil.valueOf(map.get("articl_id")));
            articl.setCode(StringUtil.valueOf(map.get("articl_code")));
            articl.setContext(StringUtil.valueOf(map.get("context")));
            articl.setLogo(StringUtil.valueOf(map.get("logo")));
            articl.setCreateTime(StringUtil.valueOf(map.get("create_time")));
            articl.setModTime(StringUtil.valueOf(map.get("mod_time")));
            articl.setCateId(StringUtil.valueOf(map.get("cate_id")));
            articl.setIsEnd(StringUtil.valueOf(map.get("isend")));
            articl.setIsColletion(StringUtil.valueOf(map.get("is_collection")));
            articl.setLikes((Integer) map.get("likes"));
            articl.setTitle(StringUtil.valueOf(map.get("title")));
            articl.setUserId(StringUtil.valueOf(map.get("user_id")));
            articl.setIsPublish(StringUtil.valueOf(map.get("ispublish")));
            articl.setUser(user);
        }
        List<FilePath> filePaths=listFilepaths(articl_id);
        List<Group> groups=listgroups(articl_id);
        articl.setFilePaths(filePaths);
        articl.setGroup(groups);
        DbUtil.close();
        return articl;
    }
    /**
     * 修改文章（只修改内容）
     */
    public int modArticl(Articl articl) throws IOException{
        String sql="update `tb_articl` set context=?,logo=?,cate_id=?,isend=?,user_id=?,title=?,ispublish=?,mod_time=now() where articl_id=?";
        int code=DbUtil.update(sql,articl.getContext(),articl.getLogo(),articl.getCateId(),articl.getIsEnd(),articl.getUserId(),articl.getTitle(),articl.getIsPublish(),articl.getId());
        return code;
    }
    /**
     * 修改文章状态
     */
    public int modArticlStatus(Articl articl){
        String sql="update `tb_Articl` set ispublish=?,mod_time=now() where articl_id=?";
        int code=DbUtil.update(sql,articl.getIsPublish(),articl.getId());
        DbUtil.close();
        return code;
    }
    /**
     * 批量删除文章（先要删除该文章的所有图片）
     */
    public int removeArticls(List list) throws Exception {
        StringBuffer stringBuffer=new StringBuffer();
        for(int i=0;i<list.size();i++){
            stringBuffer.append("\'");
            stringBuffer.append(list.get(i));
            stringBuffer.append("\',");
        }
        String sql="delete from `tb_articl` where articl_id in ("+stringBuffer.substring(0,stringBuffer.length()-1)+")";
        int code=0;
        try {
            code=DbUtil.update(sql);
        }catch (Exception e){
            e.printStackTrace();
            throw new Exception("DML异常");
        }
        DbUtil.close();
        return code;

    }

    /**
     * 修改文章的logo（删除原有路径，添加新的路径）
     */
    public int modArticlLogo(Articl articl){
        String sql="update `tb_articl` set logo=?,mod_time=now() where articl_id=?";
        int code=DbUtil.update(sql,articl.getLogo(),articl.getId());
        return code;
    }
    /**
     * 查询点赞量
     */
    public int queryLikes(String articl_id)  {
        String sql=" select likes from `tb_articl` where articl_id=?";
        List<Map<String,Object>> list=DbUtil.query(sql,articl_id);
        int toral=0;
        if(list!=null && list.size()>0){
            Map<String,Object> map=list.get(0);
            toral= (Integer) map.get("likes");
        }
        DbUtil.close();
        return toral;
    }
    /**
     * 修改点赞量
     */
    public int modLikes(Integer likes,String articlId)  {
        String sql="update `tb_articl` set likes=? where articl_id=?";
        int code=DbUtil.update(sql,likes,articlId);
        DbUtil.close();
        return code;
    }
    /**
     * 添加文章点赞
     */
    public int addArticlLikes(ArticlLikes like){
        String sql="insert into tb_articl_like(articl_id,user_id) values(?,?)";
        int code1=0;
        int code2=0;
        DbUtil.beginTransaction();
        Integer likes=queryLikes(like.getArticlId());
        try {
            code1=modLikes(likes+1,like.getArticlId());
            code2=DbUtil.update(sql,like.getArticlId(),like.getUserId());
        }catch (Exception e){
            e.printStackTrace();
            DbUtil.rollback();
        }
        return code1 & code2;
    }
    /**
     * 减少文章点赞
     */
    public int deleteArticlLikes(ArticlLikes like){
        String sql="delete from tb_articl_like where articl_id=? and user_id=?";
        int code1=0;
        int code2=0;
        Integer likes=queryLikes(like.getArticlId());
        if(likes<=0){
            return code1 & code2;
        }
        try {
            code1=modLikes(likes-1,like.getArticlId());
            code2=DbUtil.update(sql,like.getArticlId(),like.getUserId());
        }catch (Exception e){
            e.printStackTrace();
            DbUtil.rollback();
        }
        return  code1 & code2;

    }
    /**
     * 判断文章有没有点过赞
     */
    public ArticlLikes queryArticlLikes(ArticlLikes like){
        String sql="select t.* from tb_articl_like t where articl_id=? and user_id=?";
        List<Map<String,Object>> list=DbUtil.query(sql,like.getArticlId(),like.getUserId());
        ArticlLikes likes=null;
        if(list !=null && list.size()>0){
            Map<String,Object> map=list.get(0);
            likes=new ArticlLikes();
            likes.setId(StringUtil.valueOf(map.get("id")));
            likes.setArticlId(StringUtil.valueOf(map.get("articl_id")));
            likes.setUserId(StringUtil.valueOf(map.get("user_id")));
        }
        return likes;
    }
    /**
     * 给文章添加一个专题
     */
    public int addArtGroup(Articl articl){
        String sql="insert into `tb_articl_group`(articl_id,group_id) values(?,?)";
        String articlId=articl.getId();
        List<Group> groups=articl.getGroup();
        DbUtil.beginTransaction();
        int code=0;
        try{
            for(Group group:groups){
                code=DbUtil.update(sql,articlId,group.getGroupId());
            }
            DbUtil.commit();
        }catch (Exception e){
            e.printStackTrace();
            DbUtil.rollback();
        }
        return code;
    }
    /**
     * 根据时间查询文章列表
     */
    public List<Articl> getArticlByYearMonth(String year, String month) {
        String sql = "SELECT * FROM tb_articl WHERE YEAR(create_time) = ? and MONTH(create_time)=? and ispublish='1' ORDER BY create_time desc";
        List<Map<String, Object>> listArt = DbUtil.query(sql, year, month);
        List<Articl> articlList = new ArrayList<>();
        if (listArt != null && listArt.size() > 0) {
            for (Map<String, Object> map : listArt) {
                Articl articl = new Articl();
                articl.setId(StringUtil.valueOf(map.get("articl_id")));
                articl.setCode(StringUtil.valueOf(map.get("articl_code")));
                articl.setContext(StringUtil.valueOf(map.get("context")));
                articl.setLogo(StringUtil.valueOf(map.get("logo")));
                articl.setCreateTime(StringUtil.valueOf(map.get("create_time")));
                articl.setModTime(StringUtil.valueOf(map.get("mod_time")));
                articl.setCateId(StringUtil.valueOf(map.get("cate_id")));
                articl.setIsEnd(StringUtil.valueOf(map.get("isend")));
                articl.setLikes((Integer) map.get("likes"));
                articl.setTitle(StringUtil.valueOf(map.get("title")));
                articl.setUserId(StringUtil.valueOf(map.get("user_id")));
                articl.setIsPublish(StringUtil.valueOf(map.get("ispublish")));
                articlList.add(articl);
            }
        }
        DbUtil.close();
        return articlList;
    }
    /**
     * 查询连载文章
     */
   public List<Articl> getArticlNoEnd(){
       String sql = "SELECT * FROM tb_articl WHERE isend='0' and ispublish='1' and cate_id='1' ORDER BY create_time desc";
       List<Map<String, Object>> listArt = DbUtil.query(sql);
       List<Articl> articlList = new ArrayList<>();
       if (listArt != null && listArt.size() > 0) {
           for (Map<String, Object> map : listArt) {
               Articl articl = new Articl();
               articl.setId(StringUtil.valueOf(map.get("articl_id")));
               articl.setCode(StringUtil.valueOf(map.get("articl_code")));
               articl.setContext(StringUtil.valueOf(map.get("context")));
               articl.setLogo(StringUtil.valueOf(map.get("logo")));
               articl.setCreateTime(StringUtil.valueOf(map.get("create_time")));
               articl.setModTime(StringUtil.valueOf(map.get("mod_time")));
               articl.setCateId(StringUtil.valueOf(map.get("cate_id")));
               articl.setIsEnd(StringUtil.valueOf(map.get("isend")));
               articl.setLikes((Integer) map.get("likes"));
               articl.setTitle(StringUtil.valueOf(map.get("title")));
               articl.setUserId(StringUtil.valueOf(map.get("user_id")));
               articl.setIsPublish(StringUtil.valueOf(map.get("ispublish")));
               articlList.add(articl);
           }
       }
       DbUtil.close();
       return articlList;
   }

    public List<Articl> getArticlEnd(){
        String sql = "SELECT * FROM tb_articl WHERE isend='1' and ispublish='1' and cate_id='1' ORDER BY create_time desc";
        List<Map<String, Object>> listArt = DbUtil.query(sql);
        List<Articl> articlList = new ArrayList<>();
        if (listArt != null && listArt.size() > 0) {
            for (Map<String, Object> map : listArt) {
                Articl articl = new Articl();
                articl.setId(StringUtil.valueOf(map.get("articl_id")));
                articl.setCode(StringUtil.valueOf(map.get("articl_code")));
                articl.setContext(StringUtil.valueOf(map.get("context")));
                articl.setLogo(StringUtil.valueOf(map.get("logo")));
                articl.setCreateTime(StringUtil.valueOf(map.get("create_time")));
                articl.setModTime(StringUtil.valueOf(map.get("mod_time")));
                articl.setCateId(StringUtil.valueOf(map.get("cate_id")));
                articl.setIsEnd(StringUtil.valueOf(map.get("isend")));
                articl.setLikes((Integer) map.get("likes"));
                articl.setTitle(StringUtil.valueOf(map.get("title")));
                articl.setUserId(StringUtil.valueOf(map.get("user_id")));
                articl.setIsPublish(StringUtil.valueOf(map.get("ispublish")));
                articlList.add(articl);
            }
        }
        DbUtil.close();
        return articlList;
    }
    /**
     * 判断文章有没有被收藏
     */
    public Colletion queryArticlCollection(Colletion colletion){
        String sql="select t.* from tb_collection t where user_id=? and articl_id=?";
        List<Map<String,Object>> list=DbUtil.query(sql,colletion.getUser_id(),colletion.getArticl_id());
        Colletion colletion1=null;
        if(list!=null && list.size()>0){
            Map<String,Object> map=list.get(0);
            colletion1=new Colletion();
            colletion1.setId(StringUtil.valueOf(map.get("collection_id")));
            colletion1.setUser_id(StringUtil.valueOf(map.get("user_id")));
            colletion1.setArticl_id(StringUtil.valueOf(map.get("articl_id")));
        }
        return colletion1;
    }

}
